package service

import (
	"fmt"
	"go-project/common"
	"go-project/dto/requrest"
	"go-project/models"
)

type ArticleCategory struct {
}

func (ArticleCategory) FindList(article_s *requrest.ArticleCategorySearchRequest) (lists []models.ArticleCategory, count int64, err error) {
	offset := (article_s.Pagination.Page - 1) * article_s.Pagination.Limit
	var article_category_model *models.ArticleCategory
	query := common.DB.Table(article_category_model.TableName())
	if len(article_s.Name) > 0 {
		query = query.Where("name like ?", fmt.Sprintf("%%%s%%", article_s.Name))
	}
	query.Model(article_category_model).Select("count(id)").Count(&count)
	err = query.Limit(article_s.Pagination.Limit).Order("id desc").Offset(offset).Find(&lists).Error

	return
}

func (ArticleCategory) Add(request *requrest.ArticleCateInsertRequest) (uint, error) {
	var article_category models.ArticleCategory
	request.Generate(&article_category)
	result := common.DB.Create(&article_category)
	return article_category.ID, result.Error
}

func (ArticleCategory) Update(request *requrest.ArticleCateUpdateRequest) (uint, error) {
	var model models.ArticleCategory
	row := common.DB.First(&model, request.Id)
	if row.Error == nil {
		request.Generate(&model)
		result := common.DB.Save(&model)
		return model.ID, result.Error
	}
	return 0, row.Error
}

func (ArticleCategory) Del(id uint) (uint, error) {
	var model models.ArticleCategory
	result := common.DB.Delete(&model, id)
	return uint(result.RowsAffected), result.Error
}
func (ArticleCategory) Get(id uint) (models.ArticleCategory, error) {
	var model models.ArticleCategory
	result := common.DB.First(&model, id)
	return model, result.Error
}

func (ArticleCategory) BatchDelByIds(ids []int) (uint, error) {
	var model models.ArticleCategory
	result := common.DB.Delete(&model, ids)
	return uint(result.RowsAffected), result.Error
}
